﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;

namespace Dyao.Book.Web.Extensions
{
    public class BaseController : ControllerBase
    {
        protected IServiceProvider ServiceProvider => HttpContext.RequestServices;

        [NonAction]
        protected T GetRequiredService<T>()
        {
            return ServiceProvider.GetRequiredService<T>();
        }

        [NonAction]
        public void ValidateModelState()
        {
            if (!this.ModelState.IsValid)
            {
                var detail = GetRequiredService<ProblemDetailsFactory>().CreateValidationProblemDetails(HttpContext, this.ModelState);

                throw new ValidationProblemDetailsBusinessException(detail);
            }

        }
    }
}
